package lwcmyt.gateway.config;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component
public class AccessFilter implements GlobalFilter, Ordered {

    // url匹配器
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    private static final ReentrantLock lock = new ReentrantLock();

    //@Resource
    //private StringRedisTemplate stringRedisTemplate;

    @Override
    public int getOrder() {
        // TODO Auto-generated method stub
        return -500;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange);

//        ServerHttpResponse originalResponse = exchange.getResponse();
//        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
//        String accessToken = extractToken(exchange.getRequest());
//        log.info("=======请求拦截=====" + JSON.toJSONString(pathMatcher));
//        //注册接口
//        if (pathMatcher.match("/ysa-system-service/SysUserInfo/save", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======注册接口=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //部门查询
//        if (pathMatcher.match("/system/department/queryDepListSelect", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======部门查询=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //考试模块首页接口
//        if (pathMatcher.match("/ysa-exam-service/index/**", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======考试模块首页接口=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //模拟题库
//        if (pathMatcher.match("/ysa-exam-service/onlineTest/clientBankList", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======模拟题库=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //分类刷题
//        if (pathMatcher.match("/ysa-exam-service/classifySubject/queryClassify", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======分类刷题=====" + exchange);
//            return chain.filter(exchange);
//        }
//        if (pathMatcher.match("/ysa-exam-service/classifySubject/pageListClassify", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======分类刷题=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //学习资料
//        if (pathMatcher.match("/ysa-exam-service/examLearningMaterials/**", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======学习资料=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //在线课程
//        if (pathMatcher.match("/ysa-exam-service/course/getOneClassifyCascadeInfo", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======在线课程=====" + exchange);
//            return chain.filter(exchange);
//        }
//        if (pathMatcher.match("/ysa-exam-service/course/pageList", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======在线课程=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //doc
//        if (pathMatcher.match("/**/v2/api-docs/**", exchange.getRequest().getPath().value())) {
//            return chain.filter(exchange);
//        }
//        //登录
//        if (pathMatcher.match("/ysa-auth-service/login", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======登录=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //微信回调
//        if (pathMatcher.match("/ysa-base/receiveInfo", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======登录=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //门户
//        if (pathMatcher.match("/ysa-equip-service/instru/*", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //仪器公告
//        if (pathMatcher.match("/ysa-equip-service/portalNotes/*", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======登录=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //幻灯片
//        if (pathMatcher.match("/ysa-system-service/slide/list", exchange.getRequest().getPath().value())) {
//            log.info("=======幻灯片=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //内容管理
//        if (pathMatcher.match("/ysa-content/title/**", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======内容管理=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //门户设备列表
//        if (pathMatcher.match(" /ysa-equip-service/instru/*", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户设备列表=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//
//        //门户预约统计
//        if (pathMatcher.match("/ysa-order-service/SubRecordController/instruOrderstatistics", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户预约统计=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //门户设备机构
//        if (pathMatcher.match("/ysa-system-service/dept/**", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户设备机构=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //门户实验室
//        if (pathMatcher.match("/ysa-laboratory-service/laboratoryPortal/**", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户实验室=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //门户预约记录
//        if (pathMatcher.match("/ysa-order-service/SubRecordController/queryEquipPageList", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户预约记录=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //门户送样记录查询
//        if (pathMatcher.match("/ysa-order-service/SampleRecordController/queryEquipPageList", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户送样记录查询=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //部门搜索下拉
//        if (pathMatcher.match("/ysa-system-service/system/department/queryDepListSelect", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户送样记录查询=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //部门树搜索下拉
//        if (pathMatcher.match("/ysa-system-service/system/department/queryDepartmentTreeList", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======部门树搜索下拉=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //发送邮件
//        if (pathMatcher.match("/ysa-system-service/system/user/sendVerificationByUsernameEmail", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户送样记录查询=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //重置密码
//        if (pathMatcher.match("/ysa-system-service/system/user/resetUserPassword", exchange.getRequest().getPath().value())) { //放行品牌搜索下拉
//            log.info("=======门户送样记录查询=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //冻结
//        if (pathMatcher.match("/ysa-pay-service/cost/frozen", exchange.getRequest().getPath().value())) { //费用冻结
//            log.info("=======费用冻结=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //解冻
//        if (pathMatcher.match("/ysa-pay-service/cost/unfrozen", exchange.getRequest().getPath().value())) { //费用解冻
//            log.info("=======费用冻结=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //发送验证码
//        if (pathMatcher.match("/ysa-system-service/system/user/sendVerificationByUsernameEmail", exchange.getRequest().getPath().value())) { //费用解冻
//            log.info("=======发送验证码=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //系统配置
//        if (pathMatcher.match("/ysa-base/systemConfig/getSystemConfigInfo", exchange.getRequest().getPath().value())) { //费用解冻
//            log.info("=======获取系统配置=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //后台评论详情
//        if (pathMatcher.match("/ysa-equip-service/devComment/getByOrder", exchange.getRequest().getPath().value())) { //费用解冻
//            log.info("=======获取系统配置=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //仪器考核计划状态
//        if (pathMatcher.match("/ysa-equip-service/dev/devEquipAssessmentPlan/updateAssessmentState", exchange.getRequest().getPath().value())) { //仪器考核计划状态
//            log.info("=======仪器考核计划状态=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //获取设备预约检测项目
//        if (pathMatcher.match("/ysa-base-service/instruSetting/getEquipSettingProjectsPcClient", exchange.getRequest().getPath().value())) { //获取设备预约检测项目
//            log.info("=======获取设备预约检测项目=====" + exchange);
//            return chain.filter(exchange);
//        }
//        //PC客户端 查询所有仪器所属机构
//        if (pathMatcher.match("/ysa-equip-service/client/pc/GetMachineList", exchange.getRequest().getPath().value())) { //PC客户端 查询所有仪器所属机构
//            log.info("=======PC客户端 查询所有仪器所属机构=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//        //PC客户端 获取设备所有检验项目
//        if (pathMatcher.match("/ysa-equip-service/client/pc/GetExperimentList", exchange.getRequest().getPath().value())) { //PC客户端 获取设备所有检验项目
//            log.info("=======PC客户端 获取设备所有检验项目=====" + exchange);
//            return chain.filter(exchange);
//        }
//
//
//
//        ServerHttpResponseDecorator decoratedResponse = null;
////        try {
////            lock.lock();
//        decoratedResponse = getResponse(originalResponse, bufferFactory);
//        decoratedResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
////        }finally {
////            lock.unlock();
////        }
//        if (!pathMatcher.match("/ysa-auth-service/**", exchange.getRequest().getPath().value())) {
//            try {
//                if (null == accessToken || accessToken.trim().equals("")) {
//                    originalResponse.setStatusCode(HttpStatus.OK);
////                    return chain.filter(exchange.mutate().response(decoratedResponse).build());
//                    return decoratedResponse.writeWith(Flux.just(bufferFactory.allocateBuffer()));
//                }
//                Set<String> params = stringRedisTemplate.keys("*:" + accessToken);
//                if (null == params || params.size() <= 0) {
//                    originalResponse.setStatusCode(HttpStatus.OK);
////                    return chain.filter(exchange.mutate().response(decoratedResponse).build());
//                    return decoratedResponse.writeWith(Flux.just(bufferFactory.allocateBuffer()));
//                }
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
////                return chain.filter(exchange.mutate().response(decoratedResponse).build());
//                return decoratedResponse.writeWith(Flux.just(bufferFactory.allocateBuffer()));
//            }
//        }
//        return chain.filter(exchange);
    }

    protected ServerHttpResponseDecorator getResponse(ServerHttpResponse originalResponse, DataBufferFactory bufferFactory) {
        return new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
                        // probably should reuse buffers
                        log.info("=======probably should reuse buffers=====");
                        DataBufferFactory defaultDBF = new DefaultDataBufferFactory();
                        DataBuffer join = defaultDBF.join(dataBuffer);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("msg", "请重新登录");
                        jsonObject.put("code", "401");
                        String s = jsonObject.toJSONString();
                        System.out.println("响应非法报文 = " + s);
                        //TODO，s就是response的值，想修改、查看就随意而为了
                        byte[] uppedContent = s.getBytes(StandardCharsets.UTF_8);
                        //如果不重新设置长度则收不到消息。
                        this.getDelegate().getHeaders().setContentLength(uppedContent.length);
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
    }

    protected String extractToken(ServerHttpRequest request) {
        List<String> strings = request.getHeaders().get("token");
        String authToken = null;
        if (strings != null) {
            authToken = strings.get(0);
        }

        if (StringUtils.isBlank(authToken)) {
            strings = request.getQueryParams().get("access_token");
            if (strings != null) {
                authToken = strings.get(0);
            }
        }

        return authToken;
    }

}